package com.ysxsoft.wdg.ui.activity.my.qydl;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.UserInfoBean;
import com.ysxsoft.wdg.bean.response.CollectShopResponse;
import com.ysxsoft.wdg.bean.response.DaiLiBanlanceResponse;
import com.ysxsoft.wdg.bean.response.DaiLiShenQingResponse;
import com.ysxsoft.wdg.bean.response.DlLevelBean;
import com.ysxsoft.wdg.bean.response.GetCodeResponse;
import com.ysxsoft.wdg.bean.response.WxQuYuResponse;
import com.ysxsoft.wdg.bean.response.WxResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.my.PersonActivity;
import com.ysxsoft.wdg.ui.activity.my.ShopRzInputActivity;
import com.ysxsoft.wdg.util.Base64Utils;
import com.ysxsoft.wdg.util.ImageUtils;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.PayUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.camera.CameraUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.statusbar.StatusBarUtil;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.ysxsoft.wdg.widget.alertview.OnItemClickListener;
import com.ysxsoft.wdg.widget.city.CityPicker;
import com.ysxsoft.wdg.widget.city.JsonBean;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

public class QuDlInputActivity extends BaseActivity implements PayResultListener {

    public static void start(Context context) {
        Intent intent = new Intent(context, QuDlInputActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.yqm)
    EditText yqm;
    @BindView(R.id.et_id)
    EditText etId;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;
    @BindView(R.id.tv_dj)
    TextView tvDj;
    @BindView(R.id.iv_id_z)
    ImageView ivIdZ;
    @BindView(R.id.iv_id_f)
    ImageView ivIdF;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_yuE)
    TextView tvYuE;
    @BindView(R.id.iv_yuE_choose)
    ImageView ivYuEChoose;
    @BindView(R.id.tv_zfb)
    TextView tvZfb;
    @BindView(R.id.iv_zfb_choose)
    ImageView ivZfbChoose;
    @BindView(R.id.iv_wx_choose)
    ImageView ivWxChoose;

    private int payType = 1;
    private boolean isLoaded = false;
    private boolean isLeftClicked = true;
    private String leftImagePath, rightImagePath;//正反面

    @Override
    protected int getLayoutId() {
        return R.layout.activity_qu_dl_input;
    }

    @Override
    protected void initData() {
        StatusBarUtil.setStatusBarTextColor(this, true);
        initStatusBar(topView, true);
        titleContent.setText("填写信息");
        ivYuEChoose.setSelected(true);
        //解析城市数据
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        getLevels();
        getCode();
    }

    @Override
    protected void setListener() {

    }

    private String province, city, area;

    @OnClick({R.id.title_finish, R.id.tv_address, R.id.tv_dj,
            R.id.iv_id_z, R.id.iv_id_f, R.id.ll_pay_yuE,
            R.id.ll_pay_zfb, R.id.ll_pay_wx, R.id.btn_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.tv_address:
                selectAddress();
                break;
            case R.id.tv_dj:
                setPickerView();
                break;
            case R.id.iv_id_z:
                isLeftClicked = true;
                AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            new RxPermissions(QuDlInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().takeCamera(QuDlInputActivity.this);
                                        }
                                    });
                        } else if (position == 1) {
                            new RxPermissions(QuDlInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().openAlbum(QuDlInputActivity.this);
                                        }
                                    });
                        }
                    }
                }).show();
                break;
            case R.id.iv_id_f:
                isLeftClicked = false;
                AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            new RxPermissions(QuDlInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().takeCamera(QuDlInputActivity.this);
                                        }
                                    });
                        } else if (position == 1) {
                            new RxPermissions(QuDlInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().openAlbum(QuDlInputActivity.this);
                                        }
                                    });
                        }
                    }
                }).show();
                break;
            case R.id.ll_pay_yuE:
                payType = 1;
                ivYuEChoose.setSelected(true);
                ivZfbChoose.setSelected(false);
                ivWxChoose.setSelected(false);

                break;
            case R.id.ll_pay_zfb:
                payType = 2;
                ivYuEChoose.setSelected(false);
                ivZfbChoose.setSelected(true);
                ivWxChoose.setSelected(false);

                break;
            case R.id.ll_pay_wx:
                payType = 3;
                ivYuEChoose.setSelected(false);
                ivZfbChoose.setSelected(false);
                ivWxChoose.setSelected(true);
                break;
            case R.id.btn_sure:
                submit();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
//                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Default).cropPicture(QuDlInputActivity.this, path);
                if (isLeftClicked) {//正面图
                    String p=ImageUtils.compress(QuDlInputActivity.this,System.currentTimeMillis()+".png",new File(path));
                    leftImagePath = p;
                    Glide.with(QuDlInputActivity.this).load(p).into(ivIdZ);
                    commitPic(p);//上传图片
                } else {//反面图
                    String p=ImageUtils.compress(QuDlInputActivity.this,System.currentTimeMillis()+".png",new File(path));
                    rightImagePath = p;
                    Glide.with(QuDlInputActivity.this).load(path).into(ivIdF);
                    commitPic(p);
                }
            }

            @Override
            public void selectPictureFinish(String path) {
//                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Default).cropPicture(QuDlInputActivity.this, path);
                if (isLeftClicked) {//正面图
                    String p=ImageUtils.compress(QuDlInputActivity.this,System.currentTimeMillis()+".png",new File(path));
                    leftImagePath = p;
                    Glide.with(QuDlInputActivity.this).load(p).into(ivIdZ);
                    commitPic(p);//上传图片
                } else {//反面图
                    String p=ImageUtils.compress(QuDlInputActivity.this,System.currentTimeMillis()+".png",new File(path));
                    rightImagePath = p;
                    Glide.with(QuDlInputActivity.this).load(path).into(ivIdF);
                    commitPic(p);
                }
            }

            @Override
            public void cropPictureFinish(String path) {
//                if (isLeftClicked) {//正面图
//                    leftImagePath = path;
//                    Glide.with(QuDlInputActivity.this).load(path).into(ivIdZ);
//                    commitPic(leftImagePath);
//                } else {//反面图
//                    rightImagePath = path;
//                    Glide.with(QuDlInputActivity.this).load(path).into(ivIdF);
//                    commitPic(rightImagePath);
//                }
            }
        });
    }

    //选择器
    private OptionsPickerView pvOptions;
    private List<String> strList = new ArrayList<>();
    private List<DlLevelBean.DataBean> levelList = new ArrayList<>();


    //地址选择器
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private String uid, levelid, realName, shenfenNo, tele, county, money;

    private void setPickerView() {

        pvOptions = new OptionsPickerBuilder(QuDlInputActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                DlLevelBean.DataBean dataBean = levelList.get(options1);
                tvDj.setText(dataBean.getName());
                tvDj.setTextColor(Color.parseColor("#333333"));
                levelid = dataBean.getLevelid();
                money = dataBean.getService();
                tvMoney.setText(money + "元");
            }
        }).build();
        pvOptions.setPicker(strList);
        pvOptions.show();
    }

    /**
     * 城市三级联动
     */
    private void selectAddress() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                province = options1Items.get(options1).getPickerViewText();
                city = options2Items.get(options1).get(options2);
                county = options3Items.get(options1).get(options2).get(options3);

                tvAddress.setText(province + city + county);
                tvAddress.setTextColor(Color.parseColor("#333333"));
            }
        }).setDividerColor(Color.GRAY)
                //.setTextColorCenter(getResources().getColor(R.color.blue)) //设置选中项文字颜色
                .setContentTextSize(16)
                //.setTitleText("城市选择")
                .setOutSideCancelable(true)// default is true
                .build();
        //默认选择河南省
        pvOptions.setSelectOptions(15);
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        //                        Toast.makeText(RealNameActivity.this,"开始解析数据",Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据成功",Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据失败",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    /**
     * 获取等级
     */
    private void getLevels() {
        OkHttpUtils.post()
                .url(UrlHost.DAI_LEVEL)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    DlLevelBean dlLevelBean = JsonUtils.parseByGson(response, DlLevelBean.class);
                    if (dlLevelBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(dlLevelBean.getCode())) {
                        List<DlLevelBean.DataBean> dataBeans = dlLevelBean.getData();
                        levelList.clear();
                        strList.clear();
                        levelList.addAll(dataBeans);
                        for (int i = 0; i < dataBeans.size(); i++) {
                            DlLevelBean.DataBean da = dataBeans.get(i);
                            strList.add(da.getName());
                        }
                    } else {
                        ToastUtils.showToast(dlLevelBean.getMs());
                    }
                }
            }
        });
    }

    /**
     * 提交申请
     */
    private void submit() {
        if ("".equals(etName.getText().toString())) {
            ToastUtils.showToast("请填写姓名!");
            return;
        }
        if ("".equals(etId.getText().toString())) {
            ToastUtils.showToast("请填写身份证号!");
            return;
        }
        if(etId.getText().toString().length()!=18){
            ToastUtils.showToast("身份证号码格式不正确!");
            return;
        }
        if ("".equals(etPhone.getText().toString())) {
            ToastUtils.showToast("请填写手机号!");
            return;
        }
        if(etPhone.getText().toString().length()!=11){
            ToastUtils.showToast("手机号格式不正确!");
            return;
        }
        if (city == null || province == null || county == null) {
            ToastUtils.showToast("请选择城市!");
            return;
        }
        if (levelid == null) {
            ToastUtils.showToast("请选择代理等级!");
            return;
        }
        if (leftid == null) {
            ToastUtils.showToast("请上传正面身份证!");
            return;
        }
        if (rightid == null) {
            ToastUtils.showToast("请上传反面身份证!");
            return;
        }

        String image1 = Base64Utils.encodeFile(leftImagePath);
        String image2 = Base64Utils.encodeFile(rightImagePath);
        OkHttpUtils.post()
                .url(UrlHost.DAI_SUBMIT)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("code", yqm.getText().toString())
                .addParams("realname", etName.getText().toString())
                .addParams("IDnumber", etId.getText().toString())
                .addParams("mobile", etPhone.getText().toString())
                .addParams("ID_pic_1", leftid)
                .addParams("ID_pic_2", rightid)
                .addParams("province", province)
                .addParams("city", city)
                .addParams("county", county)
                .addParams("level", levelid)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    DaiLiShenQingResponse daiLiShenQingResponse = JsonUtils.parseByGson(response, DaiLiShenQingResponse.class);
                    if (daiLiShenQingResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(daiLiShenQingResponse.getCode())) {
                        String agencyid = daiLiShenQingResponse.getData();
                        switch (payType) {
                            case 1://余额
                                AlertUtils.payAlert(QuDlInputActivity.this);
                                postYuE(agencyid);
                                break;
                            case 2://支付宝
                                AlertUtils.payAlert(QuDlInputActivity.this);
                                postAliPay(agencyid);
                                break;
                            case 3://微信
//                                ToastUtils.showToast("微信暂未开通");
                                postWx(agencyid);
//                                AlertUtils.dismissAlert();
                                break;
                        }
                    } else {
                        ToastUtils.showToast(daiLiShenQingResponse.getMs());
                    }
                }
            }
        });
    }


    /**
     * 余额支付
     */
    private void postYuE(String agencyid) {
        OkHttpUtils.post()
                .url(UrlHost.DAI_PAY_BALANCE)
                .addParams("agencyid", agencyid)
                .addParams("total", money)
                .addParams("uid", SharePrefUtils.getUserId())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    DaiLiBanlanceResponse daiLiBanlanceResponse = JsonUtils.parseByGson(response, DaiLiBanlanceResponse.class);
                    if (daiLiBanlanceResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(daiLiBanlanceResponse.getCode())) {
                        ToastUtils.showToast("支付成功");
                        finish();
                    } else {
                        ToastUtils.showToast(daiLiBanlanceResponse.getMs());
                    }
                }
            }
        });
    }

    /**
     * 余额支付
     */
    private void postAliPay(String agencyid) {
        OkHttpUtils.post()
                .url(UrlHost.DAI_PAY_ALIPAY)
                .addParams("agencyid", agencyid)
                .addParams("total", money)
                .addParams("uid", SharePrefUtils.getUserId())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    DaiLiBanlanceResponse daiLiBanlanceResponse = JsonUtils.parseByGson(response, DaiLiBanlanceResponse.class);
                    if (daiLiBanlanceResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(daiLiBanlanceResponse.getCode())) {
                        String data = daiLiBanlanceResponse.getData();
                        data = data.replace("&amp;", "&");

                        PayUtils.startAlipay(QuDlInputActivity.this, handler, 0x10, data);//支付宝支付
                    } else {
                        ToastUtils.showToast(daiLiBanlanceResponse.getMs());
                    }
                }
            }
        });
    }

    /**
     * 微信支付
     */
    private void postWx(String agencyid) {
        OkHttpUtils.post()
                .url(UrlHost.DAI_PAY_WX)
                .addParams("agencyid", agencyid)
                .addParams("total", money)
                .addParams("uid", SharePrefUtils.getUserId())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    WxQuYuResponse wxQuYuResponse = JsonUtils.parseByGson(response, WxQuYuResponse.class);
                    if (wxQuYuResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(wxQuYuResponse.getCode())) {
                        WxQuYuResponse.DataBean dataBean = wxQuYuResponse.getData();
                        WxPayBean bean = new WxPayBean();
                        bean.setAppid(dataBean.getAppid());
                        bean.setNoncestr(dataBean.getNoncestr());
                        bean.setPackageX(dataBean.getPackageX());
                        bean.setPartnerid(dataBean.getPartnerid());
                        bean.setPrepayid(dataBean.getPrepayid());
                        bean.setSign(dataBean.getSign());
                        bean.setTimestamp("" + dataBean.getTimestamp());
                        com.ysxsoft.wdg.pay.PayUtils.getInstance(mContext).toWxPay(bean);
                    } else {
                        ToastUtils.showToast(wxQuYuResponse.getMs());
                    }
                }
            }
        });
    }


    //	支付宝支付结果
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x10:
                    Map<String, String> map = (Map<String, String>) msg.obj;
                    //9000支付成功  8000 正在处理中  4000 订单支付失败  5000重复请求  6001中途取消  6002网络连接出错 6004 支付结果未知  其他其他支付错误
                    if ("9000".equals(map.get("resultStatus"))) {//订单支付成功
                        Toast.makeText(QuDlInputActivity.this, "支付宝支付成功！", Toast.LENGTH_SHORT).show();
                        finish();
                    } else if ("4000".equals(map.get("resultStatus"))) {//订单支付失败
                        Toast.makeText(QuDlInputActivity.this, "支付宝支付失败！", Toast.LENGTH_SHORT).show();
                    } else if ("6001".equals(map.get("resultStatus"))) {//订单支付中途取消
                        Toast.makeText(QuDlInputActivity.this, "支付宝支付取消！", Toast.LENGTH_SHORT).show();
                    }
                    Log.e("tag", new Gson().toJson(map));
                    break;
            }
        }
    };

    private String leftid;
    private String rightid;

    /**
     * 余额支付
     */
    private void commitPic(String path) {
        mApiHelper.commitPic(path, new Observer<BaseBean<UserInfoBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<UserInfoBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    if (isLeftClicked) {
                        leftid = baseBean.getData().getId();
                    } else {
                        rightid = baseBean.getData().getId();
                    }
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    @Override
    public void onPaySuccess() {
        ToastUtils.showToast("支付成功！");
        finish();
    }

    @Override
    public void onPayError() {
        ToastUtils.showToast("支付失败！");
    }

    @Override
    public void onPayCancel() {
        ToastUtils.showToast("支付取消！");
    }

    /**
     * 获取邀请码
     */
    private void getCode() {
        OkHttpUtils.post()
                .url(UrlHost.PCODE)
                .addParams("uid", SharePrefUtils.getUserId())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    GetCodeResponse collectShopResponse = JsonUtils.parseByGson(response, GetCodeResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        String code=collectShopResponse.getData();
                        yqm.setText(code);
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

}
